package com.phiture.erp.produce.web.controller.admin;

import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialUnitResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.basic.api.service.ErpMaterialUnitApi;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceMainPlanPageReqVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceMainPlanRespVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceMainPlanSaveReqVO;
import com.phiture.erp.produce.core.service.ErpProduceMainPlanService;
import com.phiture.erp.produce.dal.entity.ErpProduceMainPlanDO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;


@Tag(name = "管理后台 - 主计划")
@RestController
@RequestMapping("/erp/main-plan")
@Validated
public class ErpProduceMainPlanController {

    @Resource
    private ErpProduceMainPlanService mainPlanService;

    @Resource
    private ErpMaterialUnitApi erpMaterialUnitApi;

    @Resource
    private ErpMaterialApi erpMaterialApi;

    @PostMapping("/create")
    @Operation(summary = "创建主计划")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:create')")
    public CommonResult<Long> createMainPlan(@Valid @RequestBody ErpProduceMainPlanSaveReqVO createReqVO) {
        return success(mainPlanService.createMainPlan(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新主计划")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:update')")
    public CommonResult<Boolean> updateMainPlan(@Valid @RequestBody ErpProduceMainPlanSaveReqVO updateReqVO) {
        mainPlanService.updateMainPlan(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除主计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:main-plan:delete')")
    public CommonResult<Boolean> deleteMainPlan(@RequestParam("id") Long id) {
        mainPlanService.deleteMainPlan(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得主计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:query')")
    public CommonResult<ErpProduceMainPlanRespVO> getMainPlan(@RequestParam("id") Long id) {
        ErpProduceMainPlanDO mainPlan = mainPlanService.getMainPlan(id);
        return success(BeanUtils.toBean(mainPlan, ErpProduceMainPlanRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得主计划分页")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:query')")
    public CommonResult<PageResult<ErpProduceMainPlanRespVO>> getMainPlanPage(@Valid ErpProduceMainPlanPageReqVO pageReqVO) {
        PageResult<ErpProduceMainPlanDO> pageResult = mainPlanService.getMainPlanPage(pageReqVO);

        if(pageResult.getList().isEmpty()) {
            return success(new PageResult<>(Collections.emptyList(), pageResult.getTotal()));
        }

        // 通过物料API获取所有物料
        Map<Long, ErpMaterialInfoResp> materialRespMap = erpMaterialApi.getMaterialMap(
                convertSet(pageResult.getList(), ErpProduceMainPlanDO::getMaterialId));

        Map<Long, ErpMaterialUnitResp> unitRespVOMap = erpMaterialUnitApi.getMaterialUnitMap(
                convertSet(pageResult.getList(), ErpProduceMainPlanDO::getUnitId));

        PageResult<ErpProduceMainPlanRespVO> result = BeanUtils.toBean(pageResult, ErpProduceMainPlanRespVO.class, planRespVO -> {
            MapUtils.findAndThen(unitRespVOMap, planRespVO.getUnitId(), unitResp -> planRespVO.setUnitName(unitResp.getName()));
            MapUtils.findAndThen(materialRespMap, planRespVO.getMaterialId(), materialResp -> {
                planRespVO.setMaterialName(materialResp.getName());
            });
        });

        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出主计划 Excel")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMainPlanExcel(@Valid ErpProduceMainPlanPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpProduceMainPlanDO> list = mainPlanService.getMainPlanPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "主计划.xls", "数据", ErpProduceMainPlanRespVO.class,
                        BeanUtils.toBean(list, ErpProduceMainPlanRespVO.class));
    }

    /**
     * 根据选择的销售订单，自动生成主计划
     *
     */
    @PostMapping("/auto-generate")
    @Operation(summary = "根据选择的销售订单，自动生成主计划")
    @PreAuthorize("@ss.hasPermission('erp:main-plan:auto-generate')")
    public CommonResult<Boolean> autoGenerateMainPlan(@RequestBody List<Long> orderIds) {
        mainPlanService.autoGenerateMainPlan(orderIds);
        return success(true);
    }

}